package com.bahiaapk;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.widget.Toast;

public class LoginTwitterActivity extends Activity{

	private static final String CONSUMER_KEY 			 = "EYPN370U6tdZINgDN413mA";


	private static final String CONSUMER_SECRET 		 = "fFHrAFcyW7EAqXabeJ7QWuj3uAFfC9q6Sf2woUQ8pc";


	private static final String PREF_ACCESS_TOKEN_SECRET = "accessTokenSecret";

	private static final String PREF_ACCESS_TOKEN 		 = "accessToken";

	public static final String	CALLBACK_SCHEME			 = "Bahiapk";
	public static final String	CALLBACK_HOST			 = "callback";
	public static final String	CALLBACK_URL			 = "twitter://callback_bahiapk"  ;


	
	private RequestToken mReqToken;


	private Twitter mTwitter;



	private SharedPreferences mPrefs;			
	
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
      
       
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
          }

         // Create a new shared preference object to remember if the user has
        mPrefs = getSharedPreferences("twitterPrefs", MODE_PRIVATE);
        // Load the twitter4j helper
        mTwitter = new TwitterFactory().getInstance();
        // Tell twitter4j that we want to use it with our app
        mTwitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
        
        
        loginNewUser();
        
    }



	

 	/**
 	  * Create a request that is sent to Twitter asking 'can our app have permission to use Twitter for this user'</br>
      * We are given back the {@link mReqToken}
      * that is a unique indetifier to this request</br>
      * The browser then pops up on the twitter website and the user logins in ( we never see this informaton
      * )</br> Twitter then redirects us to {@link CALLBACK_URL} if the login was a success</br>
      *
      */
    private void loginNewUser() {
    	try {
    		
    		mReqToken = mTwitter.getOAuthRequestToken(CALLBACK_URL);
    		
    		startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(mReqToken.getAuthenticationURL())));

  
    	} catch (TwitterException e) {
    		Toast.makeText(this, "Twitter Login error, try again later", Toast.LENGTH_SHORT).show();
    		this.finish();
    		
    	}
    } 
    
    
    
    /**
     * Catch when Twitter redirects back to our {@link CALLBACK_URL}</br>
     * We use onNewIntent as in our manifest we have singleInstance="true" if we did not the
     * getOAuthAccessToken() call would fail
     */
     @Override
     protected void onNewIntent(Intent intent) {
    	 super.onNewIntent(intent);
         
         dealWithTwitterResponse(intent);
     }
 
     /**
      * Twitter has sent us back into our app</br>
      * Within the intent it set back we have a 'key' we can use to authenticate the user
      *
      * @param intent
      */
     private void dealWithTwitterResponse(Intent intent) {
    	 Uri uri = intent.getData();
         if (uri != null && uri.toString().startsWith(CALLBACK_URL)) { // If the user has just logged in
        	 String oauthVerifier = uri.getQueryParameter("oauth_verifier");
 
             authoriseNewUser(oauthVerifier);
         }
     }
 
     /**
      * Create an access token for this new user</br>
      * Fill out the Twitter4j helper</br>
      * And save these credentials so we can log the user straight in next time
      *
      * @param oauthVerifier
      */
     private void authoriseNewUser(String oauthVerifier) {
    	 try {
    		 AccessToken at = mTwitter.getOAuthAccessToken(mReqToken, oauthVerifier);
             mTwitter.setOAuthAccessToken(at);
 
             saveAccessToken(at);
 
             // Set the content view back after we changed to a webview
           //  setContentView(R.layout.agenda_twitter);
             
             this.finish();
           //  detail();
             
   
    	 } catch (TwitterException e) {
    		 Toast.makeText(this, "Twitter auth error x01, try again later", Toast.LENGTH_SHORT).show();
    	 }
     }
 
   
 
   
 
    private void saveAccessToken(AccessToken at) {
    	String token = at.getToken();
    	String secret = at.getTokenSecret();
    	Editor editor = mPrefs.edit();
    	editor.putString(PREF_ACCESS_TOKEN, token);
    	editor.putString(PREF_ACCESS_TOKEN_SECRET, secret);
        editor.commit();
    }
      
    
   

    public void close(View view){
    	this.finish();
    }
}
